/* Classic Ladder Project */
/* Copyright (C) 2001-2010 Marc Le Douarain */
/* http://membres.lycos.fr/mavati/classicladder/ */
/* http://www.sourceforge.net/projects/classicladder */
/* July 2009 */
/* --------------------- */
/* Log book - GTK window */
/* --------------------- */
/* This library is free software; you can redistribute it and/or */
/* modify it under the terms of the GNU Lesser General Public */
/* License as published by the Free Software Foundation; either */
/* version 2.1 of the License, or (at your option) any later version. */

/* This library is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU */
/* Lesser General Public License for more details. */

/* You should have received a copy of the GNU Lesser General Public */
/* License along with this library; if not, write to the Free Software */
/* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#include <gtk/gtk.h>
#include <stdio.h>
#include <string.h>
#include "classicladder.h"
#include "global.h"
#include "edit.h"
#include "classicladder_gtk.h"
#include "vars_names.h"
#include "symbols_gtk.h"
#include "menu_and_toolbar_gtk.h"
#include "log_events_gtk.h"
#include "preferences.h"

GtkWidget *LogBookWindow;
static GtkListStore *ListStore;

enum
{
	ID_EVENT,
	TIME_START,
	TIME_END,
	SYMBOL_EVENT,
	PARAMETER_EVENT,
	TEXT_EVENT,
	TYPE_EVENT,
	NBR_INFOS
};

void TimeFormat( TypeTime * TimeValue, char * pBuff )
{
	struct tm * TimeFields;
	TimeFields = localtime( (time_t *)TimeValue );
	sprintf( pBuff, "%d/%d/%d %d:%02d:%02d", TimeFields->tm_year+1900, TimeFields->tm_mon+1, TimeFields->tm_mday,
		TimeFields->tm_hour, TimeFields->tm_min, TimeFields->tm_sec );
}

//can be called from periodic timer if content log evolved
void DisplayLogBookEvents( char OnLogContentModified )
{
	GtkTreeIter   iter;
	StrEventLog * pEvent;
	char BuffTimeStart[ 30 ];
	char BuffTimeEnd[ 30 ];
	int NbrEventsRemaining = Log.NbrEvents;
	int ScanEvent = Log.LastEvent;

	if ( OnLogContentModified && !GTK_WIDGET_VISIBLE( LogBookWindow ) )
		return;

	gtk_list_store_clear( ListStore );

	if ( InfosGUI->TargetMonitor.RemoteConnected )
	{
		// Acquire an iterator
		gtk_list_store_append( ListStore, &iter );

		// fill the element
		gtk_list_store_set( ListStore, &iter,
		TEXT_EVENT, "Not available for now on target...",
		-1);
		return;
	}

	if ( Log.NbrEvents>0  )
	{
		do
		{
		    pEvent = &Log.Event[ ScanEvent ];
			TimeFormat( &pEvent->StartTime, BuffTimeStart );
			if ( pEvent->EndTime!=0 )
				TimeFormat( &pEvent->EndTime, BuffTimeEnd );
			else
				strcpy( BuffTimeEnd, "***not finished***" );

			// Acquire an iterator
			gtk_list_store_append( ListStore, &iter );

			// fill the element
			gtk_list_store_set( ListStore, &iter,
					ID_EVENT, pEvent->iIdEvent,
				TIME_START, BuffTimeStart,
				TIME_END, BuffTimeEnd,
				SYMBOL_EVENT, ConfigEventLog[ pEvent->ConfigArrayNum ].Symbol,
				PARAMETER_EVENT, pEvent->Parameter,
				TEXT_EVENT, ConfigEventLog[ pEvent->ConfigArrayNum ].Text,
				TYPE_EVENT, ConfigEventLog[ pEvent->ConfigArrayNum ].EventType,
				-1);
			NbrEventsRemaining--;
			ScanEvent--;
			if (ScanEvent<0)
				ScanEvent = NBR_EVENTS_IN_LOG-1;
		}
		while( NbrEventsRemaining>0 );
	}
}


gint LogBookWindowDeleteEvent( GtkWidget * widget, GdkEvent * event, gpointer data )
{
// Here, we must only toggle the menu check that will call itself the function below to close the window ...
//	gtk_widget_hide( LogBookWindow );
	SetToggleMenuForLogWindow( FALSE/*OpenedWin*/ );
	// we do not want that the window be destroyed.
	return TRUE;
}

// called per toggle action menu, or at startup (if window saved open or not)...
void OpenLogBookWindow( GtkAction * ActionOpen, gboolean OpenIt )
{
	if ( ActionOpen!=NULL )
		OpenIt = gtk_toggle_action_get_active( GTK_TOGGLE_ACTION(ActionOpen) );
	if ( OpenIt )
	{
		DisplayLogBookEvents(FALSE/*OnLogContentModified*/);
		RestoreWindowPosiPrefs( "LogBook", LogBookWindow );
		gtk_widget_show( LogBookWindow );
		gtk_window_present( GTK_WINDOW(LogBookWindow) );
	}
	else
	{
		RememberWindowPosiPrefs( "LogBook", LogBookWindow, TRUE/*SaveWindowSize*/ );
		gtk_widget_hide( LogBookWindow );
	}
}
void RememberLogBookWindowPrefs( void )
{
	char WindowIsOpened = GTK_WIDGET_VISIBLE( GTK_WINDOW(LogBookWindow) );
	RememberWindowOpenPrefs( "LogBook", WindowIsOpened );
	if ( WindowIsOpened )
		RememberWindowPosiPrefs( "LogBook", LogBookWindow, TRUE/*SaveWindowSize*/ );
}

void LogBookInitGtk()
{
	GtkWidget  *scrolled_win, *vbox;
	GtkWidget *ListView;
	GtkCellRenderer   *renderer;
	long ScanCol;
	char * ColName[] = { "Id", "Start", "End", "Symbol", "Value", "Description", "TagEvent" };

	LogBookWindow = gtk_window_new( GTK_WINDOW_TOPLEVEL );
	gtk_window_set_title( GTK_WINDOW( LogBookWindow ), "Events Log" );
	gtk_signal_connect( GTK_OBJECT( LogBookWindow ), "delete_event",
		(GtkSignalFunc)LogBookWindowDeleteEvent, 0 );

	vbox = gtk_vbox_new(FALSE,0);

	/* Create a list-model and the view. */
	ListStore = gtk_list_store_new( NBR_INFOS, G_TYPE_INT, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_INT, G_TYPE_STRING, G_TYPE_INT );
	ListView = gtk_tree_view_new_with_model ( GTK_TREE_MODEL(ListStore) );

	/* Add the columns to the view. */
	for (ScanCol=0; ScanCol<NBR_INFOS; ScanCol++)
	{
		GtkTreeViewColumn *column;
		renderer = gtk_cell_renderer_text_new();
//		g_object_set(renderer, "editable", TRUE, NULL);
//TODO? gtk_entry_set_max_length(GTK_ENTRY(  ),9);
//		g_signal_connect( G_OBJECT(renderer), "edited", G_CALLBACK(Callback_TextEdited), (gpointer)ScanCol );
		column = gtk_tree_view_column_new_with_attributes( ColName[ ScanCol ], renderer, "text", ScanCol, NULL );
		gtk_tree_view_append_column( GTK_TREE_VIEW(ListView), column );
		gtk_tree_view_column_set_resizable( column, TRUE );
//////		gtk_tree_view_column_set_sort_column_id( column, ScanCol );
	}
//	avail since gtk v2.10...?
	gtk_tree_view_set_grid_lines( GTK_TREE_VIEW(ListView), GTK_TREE_VIEW_GRID_LINES_BOTH );

	scrolled_win = gtk_scrolled_window_new(NULL, NULL);
	gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW (scrolled_win),
                                    GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);
	// here we add the view to the scrolled !
	gtk_container_add(GTK_CONTAINER(scrolled_win), ListView);
	gtk_box_pack_start(GTK_BOX (vbox), scrolled_win, TRUE, TRUE, 0);

//	gtk_widget_set_size_request( SymbolsWindow, 300, 250 ); // minimum size
gtk_window_set_default_size (GTK_WINDOW (LogBookWindow), -1, 250);

	gtk_widget_show( scrolled_win );
	gtk_widget_show( ListView );
	gtk_container_add( GTK_CONTAINER(LogBookWindow), vbox );
	gtk_widget_show( vbox );

//gtk_widget_show (SymbolsWindow);
}
